package com.anivia.common.web.config.jackson;

import com.anivia.common.core.enums.BaseEnum;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JacksonStdImpl;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @author wangj
 */
@JacksonStdImpl
public class BaseEnumSerializer<T extends BaseEnum> extends JsonSerializer<T> {
    public static final BaseEnumSerializer instance = new BaseEnumSerializer();

    @Override
    public void serialize(T t, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        // 创建一个对象节点
        ObjectNode node = (ObjectNode) jsonGenerator.getCodec().createObjectNode();
        try {
            // 获取对象的getCode方法
            Method codeMethod = t.getClass().getMethod("getCode");
            // 获取对象的getDesc方法
            Method descMethod = t.getClass().getMethod("getDesc");
            // 获取对象的name方法
            Method nameMethod = t.getClass().getMethod("name");

            // 将对象的desc属性添加到节点中
            node.put("name", nameMethod.invoke(t).toString());
            // 将对象的code属性添加到节点中
            node.put("code", codeMethod.invoke(t).toString());
            // 将对象的desc属性添加到节点中
            node.put("desc", descMethod.invoke(t).toString());
        } catch (Exception e) {
            // 捕获异常并抛出运行时异常
            throw new RuntimeException(e);
        }
        // 将节点写入到jsonGenerator中
        jsonGenerator.writeTree(node);
    }
}
